package com.qf.web.servlet;





import cn.dsna.util.images.ValidateCode;
import com.qf.domain.Address;
import com.qf.domain.User;
import com.qf.service.AddressService;
import com.qf.service.UserService;
import com.qf.service.impl.AddressServiceimpl;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.Base64Utils;
import com.qf.utils.RandomUtils;
import com.qf.utils.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

//用户有关的servlet
@WebServlet(name = "UserServlet", value = "/userservlet")
public class UserServlet extends BaseServlet {
    //注册
    public String register(HttpServletRequest request, HttpServletResponse response) {
        //获取数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");

        //判断数据  是否为空   两次密码是否相等    emile是否正确   回显
        if (StringUtils.empty(username)) {
            request.setAttribute("registerMsg", "账户名为空");
            return "register.jsp";
        }
        if (StringUtils.empty(password)) {
            request.setAttribute("registerMsg", "密码不能为空");
            return "register.jsp";
        }
        if (password.length() < 6 || password.length() > 12) {
            request.setAttribute("registerMsg", "长度不匹配");
            return "register.jsp";
        }
        if (!repassword.equals(password)) {
            request.setAttribute("registerMsg", "两次密码不正确");
            return "register.jsp";
        }
        User user = new User(0, username, password, email, gender, 0, 1, RandomUtils.createActive());
        UserService userService = new UserServiceImpl();
        try {
            userService.regist(user);
            System.out.println("正常");
            return "redirect:/registerSuccess.jsp";

        } catch (Exception e) {
            System.out.println("异常");
            //成功或者失败跳转
            e.printStackTrace();
            request.setAttribute("registerMsg", "两次密码不正确");
            return "/register.jsp";
        }


    }

    //登陆
    public String login(HttpServletRequest request, HttpServletResponse response) {
        //获取数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vcode = request.getParameter("vcode");
        System.out.println("输入的=" + vcode);
        String code = (String) request.getSession().getAttribute("code");
        System.out.println("图片中的=" + code);
        //获取输入的验证码  之前是前端校验  删了  改成后端校验
        //获取加载的验证码
        //获取是否自动登陆
        String auto = request.getParameter("auto");
        //校验账户密码   验证码是否为空   验证码是否相同
        if (StringUtils.empty(username)) {
            //重定向
            request.getSession().setAttribute("msg", "账户不能为空");
            return "/login.jsp";
        }
        if (StringUtils.empty(password)) {
            request.getSession().setAttribute("msg", "密码不能为空");
            return "/login.jsp";
        }
        if (StringUtils.empty(vcode)) {
            request.getSession().setAttribute("msg", "验证码不能为空");
            return "/login.jsp";
        }
        if (!code.equalsIgnoreCase(vcode)) {
            request.getSession().setAttribute("msg", "验证码不正确");
            return "/login.jsp";
        }
        //创建业务对象
        UserService userService = new UserServiceImpl();
        //调用login方法
        try {
            User loginUser = userService.login(username, password);
            if (loginUser == null || loginUser.equals("")) {
                request.getSession().setAttribute("msg", "账户密码不正确");
                return "redirect:/login.jsp";
            } else {
                if (auto == null) {
                    //不成功则返回
                    // 不成功则删除cookie 防止下一个用户登陆但是没有勾选自动登陆但是登陆的上一个用户的信息
                    Cookie cookie = new Cookie("userinfo", "");
                    cookie.setHttpOnly(true);
                    cookie.setMaxAge(0);
                    cookie.setPath(request.getContextPath());
                    response.addCookie(cookie);

                } else {
                    String s = username + "#" + password;
                    String encode = Base64Utils.encode(s);
                    Cookie cookie = new Cookie("userinfo", encode);
                    cookie.setMaxAge(60 * 60 * 24 * 14);
                    cookie.setPath(request.getContextPath());
                    response.addCookie(cookie);
                    request.getSession().setAttribute("user", loginUser);
                }

                return "/index.jsp";
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", e.getMessage());
            return "/login.jsp";
        }

        //成功则登陆
        //创建一个cookie   beans64加密  时间，防止脚本  上下文路径
        //加一个session  把对象传过去   因为前端需要index当中


    }

    //检查用户是否存在
    public String checkUserName(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String username = request.getParameter("username");
        if (StringUtils.empty(username)) {
            response.getWriter().write("1");
            return null;
        }
        UserService userService = new UserServiceImpl();
        boolean b = userService.checkUserName(username);
        if (b) {
            response.getWriter().write("1");//1 表示存在
        } else {
            response.getWriter().write("0");//0 表示不存在
        }
        return null;
    }

    //验证码
    public String code(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //解决缓存问题
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        //验证码

       ValidateCode validateCode = new ValidateCode(120, 30, 4, 30);
        String code = validateCode.getCode();
        request.getSession().setAttribute("code", code);
        validateCode.write(response.getOutputStream());
        return null;
    }

    //注销
    public String logOut(HttpServletRequest request, HttpServletResponse response) {
        //删除session user
        request.getSession().removeAttribute("user");
        //删除cookie中的 userinfo
        Cookie cookie = new Cookie("userinfo", "");
        cookie.setHttpOnly(true);
        cookie.setMaxAge(0);
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);
        return "redirect:/index.jsp";
    }
    //获取地址
//    public String
    public String getAddress(HttpServletRequest request, HttpServletResponse response){
        //获取收获地址
        User user = (User) request.getSession().getAttribute("user");
        if (user==null){
            request.setAttribute("msg","请先登陆再添加地址");
            return "/index.jsp";
        }else {
            AddressService addressService=new AddressServiceimpl();
            List<Address> addresses = addressService.selectUserAddress(user.getId());
            for (Address address:addresses){
                System.out.println(address.toString());
            }
            request.setAttribute("addList" ,addresses);
            return "/self_info.jsp";
        }

    }
    //添加地址
    public String addAddress(HttpServletRequest request, HttpServletResponse response){
        User user = (User) request.getSession().getAttribute("user");
        if (user==null){
            request.setAttribute("msg","请先登陆再添加地址");
            return "/index.jsp";
        }else {
            String name = request.getParameter("name");
            String phone = request.getParameter("phone");
            String detail = request.getParameter("detail");
            if (StringUtils.empty(name)){
                request.setAttribute("msg","名字不能为空");
                return "/self_info.jsp";
            }
            if (StringUtils.empty(phone)){
                request.setAttribute("msg","电话不能为空");
                return "/self_info.jsp";
            }
            if (StringUtils.empty(detail)){
                request.setAttribute("msg","地址不能为空");
                return "/self_info.jsp";
            }
            Address address=new Address(0,detail,name,phone,user.getId(),0);
            AddressService addressService=new AddressServiceimpl();
            try {
                addressService.setAddribute(address);
                return "redirect:/userservlet?method=getAddress";
            }catch (Exception e){
                e.printStackTrace();
                request.setAttribute("msg","添加失败");
                return "/self_info.jsp";
            }

        }

    }
    //删除地址
    public String deleteAddress(HttpServletRequest request, HttpServletResponse response){
        User user = (User) request.getSession().getAttribute("user");
        if (user==null){
            request.setAttribute("msg","请先登陆再添加地址");
            return "/index.jsp";
        }else {
            String id = request.getParameter("id");
            if (StringUtils.empty(id)){
                request.setAttribute("msg","地址信息错误");
                return "/self_info.jsp";
            }
            AddressService addressService=new AddressServiceimpl();
            try {
                addressService.deleteAddressUserone(Integer.parseInt(id));
                return "redirect:/userservlet?method=getAddress";
            }catch (Exception e){
                e.printStackTrace();
                request.setAttribute("msg","删除失败");
                return "/self_info.jsp";
            }

        }
    }
    //修改地址
    public String updateAddress(HttpServletRequest request, HttpServletResponse response){
        User user = (User) request.getSession().getAttribute("user");
        if (user==null){
            request.setAttribute("msg","请先登陆再添加地址");
            return "/index.jsp";
        }else {
            String id = request.getParameter("id");
            String name = request.getParameter("name");
            String phone = request.getParameter("phone");
            String detail = request.getParameter("detail");
            String level = request.getParameter("level");
            if (StringUtils.empty(id)){
                request.setAttribute("msg","id不能为空");
                return "/self_info.jsp";
            }
            if (StringUtils.empty(name)){
                request.setAttribute("msg","用户不能为空");
                return "/self_info.jsp";
            }
            if (StringUtils.empty(phone)){
                request.setAttribute("msg","电话不能为空");
                return "/self_info.jsp";
            }
            if (StringUtils.empty(detail)){
                request.setAttribute("msg","地址不能为空");
                return "/self_info.jsp";
            }
            if (StringUtils.empty(level)){
                request.setAttribute("msg","状态显示错误");
                return "/self_info.jsp";
            }
            Address address=new Address(Integer.parseInt(id),detail,name,phone,user.getId(),Integer.parseInt(level));
            AddressService addressService=new AddressServiceimpl();
            try {
                addressService.updateUserAddressone(address);
                return "redirect:/userservlet?method=getAddress";
            }catch (Exception e){
                e.printStackTrace();
                request.setAttribute("msg","修改失败");
                return "/self_info.jsp";
            }
        }
    }
    //状态码修改
    public String defaultAddress(HttpServletRequest request, HttpServletResponse response){
        User user = (User) request.getSession().getAttribute("user");
        if (user==null){
            request.setAttribute("msg","请先登陆，才能修改地址");
            return "/index.jsp";
        }else {
            String id = request.getParameter("id");
            if (StringUtils.empty(id)){
                request.setAttribute("msg","获取地址失败");
                return "/self_info.jsp";
            }
            Integer id1 = Integer.parseInt(id);
            AddressService addressService=new AddressServiceimpl();
            try {
//                Integer level = (Integer) addressService.selectUserAddresslevel(id1);

                addressService.updatelevel(id1,user.getId());

                return "redirect:/userservlet?method=getAddress";
            }catch (Exception e){
                e.printStackTrace();
                request.setAttribute("msg","状态码修改失败");
                return "/self_info.jsp";
            }
        }



    }
}
